package com.cuitrip.business.home.travel;

import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.cuitrip.apiservice.TrackBusiness;
import com.cuitrip.apiservice.TripBusiness;
import com.cuitrip.apiservice.model.ApiManager;
import com.cuitrip.business.home.favorite.TravelTrip;
import com.cuitrip.business.home.favorite.ui.FavAnimation;
import com.cuitrip.business.home.recommend.model.RecommendTravelTrip;
import com.cuitrip.business.home.travel.model.SelectInfo;
import com.cuitrip.business.home.travel.model.SortExp;
import com.cuitrip.business.home.travel.ui.TravelTripHolderView;
import com.cuitrip.business.home.trip.model.RecommendOutData;
import com.cuitrip.business.search.SearchActivity;
import com.cuitrip.business.track.TrackProxy;
import com.cuitrip.business.tripservice.ui.IconTextView;
import com.cuitrip.component.autoload.AutoLoadScrollListener;
import com.cuitrip.component.popupmenu.PopupMenu;
import com.cuitrip.component.popupmenu.PopupMenuItem;
import com.cuitrip.component.statelayout.StateLayout;
import com.cuitrip.service.R;
import com.cuitrip.util.ListUtil;
import com.cuitrip.util.track.TrackUtil;
import com.lab.adapter.BaseHolderView;
import com.lab.adapter.HolderViewAdapter;
import com.lab.adapter.animation.SwingBottomInAnimationAdapter;
import com.lab.app.BaseActivity;
import com.lab.app.customui.CustomUiConfig;
import com.lab.app.customui.CustomUiFragment;
import com.lab.image.process.MakeImageUtil;
import com.lab.network.config.CtResponseCode;
import com.lab.network.model.CtApiResponse;
import com.lab.network.model.IProxyCallback;
import com.lab.network.model.ProxyResult;
import com.lab.network.proxy.ApiProxy;
import com.lab.utils.ArrayUtil;
import com.lab.utils.MessageUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.Bind;

public class TravelTripListFragment extends CustomUiFragment implements SwipeRefreshLayout.OnRefreshListener, Runnable, IProxyCallback {

    private static final String KEY_ITEM_LIST = "KEY_ITEM_LIST";


    public static final int RECOMMEND_MODE = 0x01;

    public static final int SEARCH_MODE = 0x02;

    public static final int INFLATE_MODE = 0x03;

    @Bind(R.id.ct_list)
    ListView mListView;

    @Bind(R.id.refresh_layout)
    SwipeRefreshLayout refreshLayout;

    @Bind(R.id.state_layout)
    StateLayout mStateLayout;

    //1.4新增
    @Bind(R.id.sort_text_item)
    TextView sortText;

    @Bind(R.id.rl_sort)
    RelativeLayout mSortLayout;

    @Bind(R.id.sort_icon_item)
    IconTextView sortArrowIcon;

    @Bind(R.id.background)
    ImageView backgroundImage;

    FavAnimation mFavAnimation;

    private SortExp mSortExp;
    private String keyWords;
    private String cityAbbr;
    private String from;
    private String title;
    private SelectInfo selectInfo;

    private boolean isClick;
    private ArrayList<String> sortValues;
    private ArrayList<String> sortKeys;
    private View view;

    private int mCurrentMode = RECOMMEND_MODE;

    private HolderViewAdapter adapter;

    private List<TravelTrip> dataList = new ArrayList<>();


    public static final int PAGE_SIZE = 10;

    private int start = 0;

    private int initialMode = RECOMMEND_MODE;

    private ApiProxy mApiProxy = new ApiProxy(this);


    private AutoLoadScrollListener autoLoadScrollListener = new AutoLoadScrollListener(this);
    private RecommendOutData mRecommendOutData;
    private String searchTag;


    public TravelTripListFragment() {
        mCurrentMode = RECOMMEND_MODE;
        initialMode = RECOMMEND_MODE;
    }

    public static TravelTripListFragment newInstance(String keyWords, String cityAbbr, String from, String title) {
        TravelTripListFragment travelTripListFragment = new TravelTripListFragment();
        Bundle bundle = new Bundle();
        bundle.putString("keyWords", keyWords);
        bundle.putString("cityAbbr", cityAbbr);
        bundle.putString("from", from);
        bundle.putString("title", title);
        travelTripListFragment.setArguments(bundle);
        return travelTripListFragment;
    }

    private String currentSortMethod;
    private String currentSortKey = "service_default_rank";


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (getArguments() != null) {
            this.keyWords = getArguments().getString("keyWords");
            this.cityAbbr = getArguments().getString("cityAbbr");
            this.from = getArguments().getString("from");
            this.title = getArguments().getString("title");
            searchTag = getArguments().getString(SearchActivity.TAG);
            selectInfo = new SelectInfo();
            String searchParams = getArguments().getString(TravelTripListActivity.SEARCH_PARAMS_KEY);
            JSONObject jsonObject = JSONObject.parseObject(searchParams);
            if (jsonObject != null) {
                for (Map.Entry<String, Object> entry : jsonObject.entrySet()) {
                    //        去除keyword和cityAbbr
                    String key = entry.getKey();
                    if (!"cityAbbr".equals(key) && !"keyword".equals(key)) {
                        selectInfo.search.put(key, entry.getValue());
                    }
                }
            }
            if (TextUtils.isEmpty(keyWords) && TextUtils.isEmpty(cityAbbr)) {
                mCurrentMode = RECOMMEND_MODE;
                initialMode = RECOMMEND_MODE;
            } else {
                mCurrentMode = SEARCH_MODE;
                initialMode = SEARCH_MODE;
            }
        }

        return super.onCreateView(inflater, container, savedInstanceState, R.layout.travel_trip_list);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (mFavAnimation != null) {
            mFavAnimation.detach();
            mFavAnimation = null;
        }
    }

    public void initView() {
        initLikeAnimation();
        ButterKnife.bind(this, getView());
        autoLoadScrollListener.setLoadingView(ListUtil.setupLoadingFooter(getHostActivity().getLayoutInflater(), mListView));
        setBottleLineVisibility(false);

        adapter = new HolderViewAdapter(getActivity(), dataList, TravelTripHolderView.class);
        adapter.setHolderViewCallback(new HolderViewAdapter.HolderViewCallback() {
            @Override
            public void onHolderViewInvalidate(BaseHolderView holderView, int position) {
                if (holderView instanceof TravelTripHolderView) {
                    TravelTripHolderView cardItemHolderView = (TravelTripHolderView) holderView;
                    cardItemHolderView.setPage(position / PAGE_SIZE);
                    List<String> ids = new ArrayList<String>();
                    for (TravelTrip trip : dataList) {
                        ids.add(String.valueOf(trip.getSid()));
                    }
                    cardItemHolderView.setCurrentList(ids);
                }

            }
        });
        SwingBottomInAnimationAdapter swingBottomInAnimationAdapter = new SwingBottomInAnimationAdapter(adapter);
        swingBottomInAnimationAdapter.setAbsListView(mListView);
        swingBottomInAnimationAdapter.setAnimationDurationMillis(500);
        mListView.setAdapter(swingBottomInAnimationAdapter);
    }

    /**
     * 初始化收藏动画
     */
    private void initLikeAnimation() {
        if (mFavAnimation == null) {
            mFavAnimation = new FavAnimation(getActivity().getWindow()) {
                @Override
                public int getTextResource() {
                    return R.string.fav_full_icon;
                }
            };
            mFavAnimation.attach();
        }
    }

    private void getSortList() {
        TripBusiness.getSortList(mApiProxy);
    }

    public void initData() {
        getSortList();
        mStateLayout.changeState(StateLayout.State.Loading);
        refreshTripList(currentSortKey);
        TrackProxy.getInstance().reviewPage(TrackBusiness.Source.SERVICE_LIST, "");
    }

    public void initListener() {
        refreshLayout.setOnRefreshListener(this);
        mListView.setOnScrollListener(autoLoadScrollListener);
        mSortLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showSortList();
            }
        });

        mStateLayout.setOnClickStateLayoutListener(new StateLayout.OnClickStateLayoutListener() {
            @Override
            public void onClick(StateLayout.State state) {
                changeLoadMode(initialMode);
                refreshTripList(currentSortKey);
                getSortList();
            }

        });


    }

    private void showSortList() {
        Bitmap bitmap = MakeImageUtil.takeScreenShot(getHostActivity());
        backgroundImage.setImageBitmap(bitmap);
        backgroundImage.setVisibility(View.VISIBLE);
        final List<PopupMenuItem> popupMenuItemList = new ArrayList<PopupMenuItem>();
        for (String sortMethod : sortValues) {
            PopupMenuItem popupMenuItem = new PopupMenuItem(sortMethod);
            popupMenuItemList.add(popupMenuItem);
            if (sortMethod.equals(currentSortMethod)) {
                popupMenuItem.setSelected(true);
            }
        }

        PopupMenu popupMenu = PopupMenu.getInstance(getHostActivity(), popupMenuItemList, new PopupMenu.PopupMenuCallback() {
            @Override
            public boolean onPopupMenuItemClick(int position, PopupMenuItem popupMenuItem) {
                currentSortMethod = sortValues.get(position);
                currentSortKey = sortKeys.get(position);
                sortText.setText(currentSortMethod);
                refreshTripList(currentSortKey);
                return false;
            }

            @Override
            public void onPopupMenuStateChanged(boolean isShow) {
                if (isShow) {
                    sortArrowIcon.setText(getString(R.string.arrow_up_icon));
                    isClick = false;

                } else {
                    sortArrowIcon.setText(getString(R.string.arrow_down_icon));
                    isClick = true;
                    backgroundImage.setVisibility(View.GONE);
                }
            }
        });

        popupMenu.show(mSortLayout);

    }

    public void onDestroy() {
        super.onDestroy();
        if (refreshLayout != null) {
            refreshLayout.setRefreshing(false);
        }
    }

    private void inflateList(List<RecommendTravelTrip> tempList) {
        if (start == 0) {
            dataList.clear();
        }
        dataList.addAll(tempList);
        adapter.notifyDataSetChanged();
        if (dataList.isEmpty()) {
            mStateLayout.changeState(StateLayout.State.Empty);
        } else {
            if (start == 0){
                mListView.setSelection(0);
            }
            mStateLayout.changeState(StateLayout.State.INIT);
        }
        autoLoadScrollListener.setEnable(true);
    }


    private void refreshTripList(String sortKey) {
        start = 0;
        if (mCurrentMode == RECOMMEND_MODE) {
            TripBusiness.getTravelTripList(mApiProxy, "", "", start, PAGE_SIZE, from, sortKey, selectInfo);
        } else if (mCurrentMode == SEARCH_MODE) {
            if (!selectInfo.isEmpty()) {
                if (!TextUtils.isEmpty(keyWords)) {
                    TrackUtil.trackScreenName("/search/results/filtered");
                } else if (!TextUtils.isEmpty(cityAbbr)) {
                    TrackUtil.trackScreenName("/%s/%s/filtered", "TW", cityAbbr);
                }
            }
            if (!TextUtils.isEmpty(cityAbbr)) {
                TrackUtil.trackScreenName("/%s/%s/sort/%S", "TW", cityAbbr, sortKey);
            }

            TripBusiness.getTravelTripList(mApiProxy, cityAbbr, keyWords, start, PAGE_SIZE, from, sortKey, selectInfo);
        } else {
            TripBusiness.getTravelTripList(mApiProxy,
                    "", "", start, PAGE_SIZE, from, sortKey, null);
        }
    }


    @Override
    public void onRefresh() {
        refreshLayout.setRefreshing(true);
        refreshTripList(currentSortKey);
    }

    @Override
    public boolean initCloseTopBar() {
        return false;
    }



    @Override
    public void onTopbarRightPress() {
        //获取items
        getItemList(mRecommendOutData);
        String sourceUri = getArguments().getString(BaseActivity.SOURCE_URI_KEY);
        TravelTripListSelectFragment fragment = TravelTripListSelectFragment.newInstance(selectInfo);
        Bundle args = fragment.getArguments();
        if (args == null) {
            args = new Bundle();
        }
        args.putString(BaseActivity.SOURCE_URI_KEY, sourceUri);
        args.putString(SearchActivity.TAG,searchTag);
        fragment.setArguments(args);
        fragment.setSelectCallback(new SelectCallback() {
            @Override
            public void onResultBack(SelectInfo selectInfo) {
//                更新selectInfo，不使用的原因是selectInfo中的categroy等值会丢失
                TravelTripListFragment.this.selectInfo.setFilterInfoList(selectInfo.getFilterInfoList());
                changeLoadMode(initialMode);
                refreshTripList(currentSortKey);
            }
        });

        if (!TextUtils.isEmpty(keyWords)) {
            TrackUtil.trackScreenName("/search/results/filter");
        } else if (!TextUtils.isEmpty(cityAbbr)) {
            TrackUtil.trackScreenName("/%s/%s/filter", "TW", cityAbbr);
        }
        getHostActivity().openFragment(fragment, R.id.container, TravelTripListSelectFragment.class.getName(), true);
    }

    private void getItemList(RecommendOutData data) {
        if (data==null){
            return;
        }
        selectInfo.facetList.addAll(data.getFacetList());
    }

    @Override
    public void onTopbarLeftPress() {
        getHostActivity().onBackPressed();
    }


    @Override
    public CustomUiConfig initCustomUiConfig() {
        CustomUiConfig customUiConfig = new CustomUiConfig();
        customUiConfig.mRightStyle = CustomUiConfig.AreaStyle.ICON_STYLE;
        customUiConfig.mTopbarMiddleAreaName = title;
        customUiConfig.mTopbarLeftAreaName = getString(R.string.back_icon);
        customUiConfig.mDisMissTopbarBottomLine = true;
        return customUiConfig;
    }


    public void setBottleLineVisibility(boolean flag) {
        if (!flag) {
            getHostActivity().removeView(R.id.bar_bottom_line);
        }
    }

    @Override
    public void run() {
        autoLoadScrollListener.setEnable(false);
        start = dataList.size();
        autoLoadScrollListener.onLoadChanged(true);
        if (mCurrentMode == RECOMMEND_MODE) {
            TripBusiness.getTravelTripList(mApiProxy, "", "", start, PAGE_SIZE, from, currentSortKey, selectInfo);
        } else if (mCurrentMode == SEARCH_MODE) {
            TripBusiness.getTravelTripList(mApiProxy, cityAbbr, keyWords, start, PAGE_SIZE, from, currentSortKey, selectInfo);
        } else if (mCurrentMode == INFLATE_MODE) {
            TripBusiness.getTravelTripList(mApiProxy, "", "", start, PAGE_SIZE, from, currentSortKey, selectInfo);
        }
    }

    private void changeLoadMode(int mode) {
        this.mCurrentMode = mode;
    }

    private void handleHeadView() {
        if (mCurrentMode != INFLATE_MODE) {
            mListView.removeHeaderView(view);
            mTopbarRightArea.setText(getString(R.string.select_icon));
            refreshLayout.setEnabled(true);
        } else {
            refreshLayout.setEnabled(false);
        }
        if (mCurrentMode != INFLATE_MODE && !ArrayUtil.isNullOrEmpty(sortValues)) {
            mSortLayout.setVisibility(View.VISIBLE);
        } else {
            mSortLayout.setVisibility(View.GONE);
        }
    }

    private void handleEmptySearchResult() {
        if (mCurrentMode == SEARCH_MODE && !TextUtils.isEmpty(keyWords) && (selectInfo == null || selectInfo.isEmpty())) {
            mTopbarRightArea.setVisibility(View.GONE);
            mStateLayout.changeState(StateLayout.State.INIT);
            view = getLayoutInflater(null).inflate(R.layout.headview_trip_list, null);
            IconTextView btnClose = (IconTextView) view.findViewById(R.id.close);
            btnClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mListView.removeHeaderView(view);
                }
            });
            mListView.addHeaderView(view);
            changeLoadMode(INFLATE_MODE);
            refreshTripList("-like");
        } else {
            mStateLayout.changeState(StateLayout.State.Empty);
        }
    }

    @Override
    public boolean onProxyResult(ProxyResult<?> result) {
        if (!isAdded()) {
            return false;
        }
        CtApiResponse response = (CtApiResponse) result.getData();
        refreshLayout.setRefreshing(false);
        //处理行程搜索结果
        if (ApiManager.SERVICE_SEARCH.equals(response.getApiName())) {
            handleHeadView();
            autoLoadScrollListener.onLoadChanged(false);
            //当结果正常，填充list
            if (response != null && response.code == CtResponseCode.RESULT_OK) {
                if (response.result instanceof RecommendOutData) {
                    mRecommendOutData = (RecommendOutData) response.result;
                    List<RecommendTravelTrip> list = mRecommendOutData.getLists();
                    inflateList(list);
                }
            } else {
                //结果异常时，处理异常页面
                mListView.removeHeaderView(view);
                if (start != 0) {
                    return false;
                }
                //处理无结果页面
                if (response != null && response.code == 201) {
                    handleEmptySearchResult();
                } else {
                    MessageUtils.showToast(response.msg);
                    mStateLayout.changeState(StateLayout.State.NoNetwork);
                }
            }
        } else if (ApiManager.SEARCH_EXP.equals(response.getApiName())) {
            if (response != null && response.code == CtResponseCode.RESULT_OK) {
                if (response.result instanceof SortExp) {
                    sortValues = new ArrayList<String>();
                    sortKeys = new ArrayList<String>();
                    mSortExp = (SortExp) response.result;
                    ArrayList<SortExp.SortInfo> sortInfos = mSortExp.getSortExp();
                    for (SortExp.SortInfo sortInfo : sortInfos) {
                        String value = sortInfo.value;
                        sortValues.add(value);
                        sortKeys.add(sortInfo.key);
                    }
                    if (sortInfos.size() > 0) {
                        currentSortMethod = sortValues.get(0);
                        currentSortKey = sortKeys.get(0);
                        sortText.setText(currentSortMethod);
                        mSortLayout.setVisibility(View.VISIBLE);
                    } else {
                        mSortLayout.setVisibility(View.GONE);
                    }
                }
            } else {
                MessageUtils.showToast(response.msg);
            }
        }
        return false;
    }

    public interface SelectCallback {

        public void onResultBack(SelectInfo selectInfo);

    }


}
